package com.zhuoxin.dao.system;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.zhuoxin.bean.system.SysRole;
import com.zhuoxin.bean.system.SysRoleUser;
import com.zhuoxin.bean.system.SysRoleUserSO;
import com.zhuoxin.bean.system.SysUser;
import com.zhuoxin.dao.BaseDAOImpl;

public class SysRoleUserDAOImpl extends BaseDAOImpl<SysRoleUser, SysRoleUserSO> implements SysRoleUserDAO {

	@Override
	public String getHqlWhere(SysRoleUserSO so) {
		StringBuffer where=new StringBuffer();
		
		if(so.getUser()!=null && so.getUser().getId()!=null){
			where.append(" and user.id=:userId");
		}
		
		if(so.getRole()!=null && so.getRole().getId()!=null){
			where.append(" and role.id=:roleId");
		}
		return where.toString();
	}

	@Override
	public void setCriteriaParams(Criteria criteria, SysRoleUserSO so) {
		if(so.getRole()!=null){
			criteria.createAlias("role", "r");
			if(so.getRole().getId()!=null){
				criteria.add(Restrictions.eq("r.id", so.getRole().getId()));
			}
		}
		
		if(so.getUser()!=null){
			criteria.createAlias("user", "u");
			if(so.getUser().getId()!=null){
				criteria.add(Restrictions.eq("u.id", so.getUser().getId()));
			}
		}
	}

	@Override
	public void setQueryParams(Query query, SysRoleUserSO so) {
		if(so.getUser()!=null && so.getUser().getId()!=null){
			query.setParameter("userId", so.getUser().getId());
		}
		
		if(so.getRole()!=null && so.getRole().getId()!=null){
			query.setParameter("roleId", so.getRole().getId());
		}
		
	}

	@Override
	public void switchVO2PO(SysRoleUser po, SysRoleUserSO so) {
		if(so.getRole()!=null && so.getRole().getId()!=null){
			SysRole role=findById(SysRole.class, so.getRole().getId());
			po.setRole(role);
		}
		
		if(so.getUser()!=null && so.getUser().getId()!=null){
			SysUser user=findById(SysUser.class, so.getUser().getId());
			po.setUser(user);
		}
	}
	
	public void delete(SysRoleUserSO so){
		Session session=getHibernateTemplate().getSessionFactory().getCurrentSession();
		Transaction transaction=session.beginTransaction();
		String hql="delete from SysRoleUser where 1=1"+getHqlWhere(so);
		Query query=session.createQuery(hql);
		setQueryParams(query, so);
		query.executeUpdate();
		transaction.commit();
	}
}
